package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.service.RequestService;
import com.tanhua.dubbo.server.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Date;

@Slf4j
@Service(version = "1.0.0")
public class HuanXinApiImpl implements HuanXinApi {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanXinUserMapper huanXinUserMapper;

    /**
     * 获取环信token（获取管理员权限）
     * @return
     */
    @Override
    public String getToken() {
        return tokenService.getToken();
    }

    //==============================================================================

    /**
     * 注册环信用户
     * 参见：http://docs-im.easemob.com/im/server/ready/user#%E6%B3%A8%E5%86%8C%E5%8D%95%E4%B8%AA%E7%94%A8%E6%88%B7_%E5%BC%80%E6%94%BE
     * @param userId 用户id
     * @return
     */
    @Override
    public Boolean register(Long userId) {
        //1.构建请求地址路径    http://a1.easemob.com/1109210525065665/sy-tanhua/users
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users";

        //2.构建请求参数 - 构建HuanXinUser对象
        HuanXinUser huanXinUser = new HuanXinUser();
        huanXinUser.setUsername("HX_" + userId);        //环信用户名
        huanXinUser.setPassword(IdUtil.simpleUUID());   //随机生成的环信密码

        //3.调用requestService发起请求
        HttpResponse response = requestService.execute(targetUrl, JSONUtil.toJsonStr(Arrays.asList(huanXinUser)), Method.POST);

        //4.判断请求是否成功
        if (response.isOk()) {
            //4.1 证明请求发送成功，表示环信用户账号注册成功，本地留痕，将对应环信账号信息保存到本地mysql数据库中
            huanXinUser.setUserId(userId);                      //该环信用户对应本地数据库中用户id
            huanXinUser.setCreated(new Date());                 //创建时间
            huanXinUser.setUpdated(huanXinUser.getCreated());   //修改事件

            //4.2 将数据保存到mysql数据库中
            huanXinUserMapper.insert(huanXinUser);

            return true;
        }

        return false;
    }

    /**
     * 根据用户id去查询环信账号信息 - id：用户id
     * @param userId
     * @return
     */
    @Override
    public HuanXinUser queryHuanXinUser(Long userId) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);                      //select * from tb_huanxin_user where user_id = ?
        return huanXinUserMapper.selectOne(wrapper);
    }

    /**
     * 根据用户在环信中用户ID(也就是mysql中保存username)去查询环信账号信息
     * @param userName
     * @return
     */
    @Override
    public HuanXinUser queryUserByUserName(String userName) {
        QueryWrapper<HuanXinUser> wrapper = new QueryWrapper<>();   //select * from tb_huanxin_user where username = ? (HX_1)
        wrapper.eq("username", userName);
        return huanXinUserMapper.selectOne(wrapper);
    }

    //==============================================================================

    /**
     * 添加好友（双向好友关系）
     * 参见：http://docs-im.easemob.com/im/server/ready/user#%E6%B7%BB%E5%8A%A0%E5%A5%BD%E5%8F%8B
     * @param userId   自己的id
     * @param friendId 好友的id
     * @return
     */
    @Override
    public Boolean addUserFriend(Long userId, Long friendId) {
        //1.构建请求路径  地址路径中用户名为 环信系统中保存的[用户ID] 例：HX_1
        String targetUrl = huanXinConfig.getUrl()
                + huanXinConfig.getOrgName() + "/"
                + huanXinConfig.getAppName() + "/users/HX_" + userId
                + "/contacts/users/HX_" + friendId;
        try {
            //2.发送请求添加好友信息
            return requestService.execute(targetUrl, null, Method.POST).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 添加失败
        return false;
    }

    /**
     * 删除好友关系（双向删除）
     * 参见：http://docs-im.easemob.com/im/server/ready/user#%E7%A7%BB%E9%99%A4%E5%A5%BD%E5%8F%8B
     * @param userId   自己的id
     * @param friendId 好友的id
     * @return
     */
    @Override
    public Boolean removeUserFriend(Long userId, Long friendId) {
        //1.构建请求路径  地址路径中用户名为 环信系统中保存的[用户ID] 例：HX_1
        String targetUrl = huanXinConfig.getUrl()
                + huanXinConfig.getOrgName() + "/"
                + huanXinConfig.getAppName() + "/users/HX_" + userId
                + "/contacts/users/HX_" + friendId;
        try {
            //2.发送请求删除好友信息
            return requestService.execute(targetUrl, null, Method.DELETE).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 添加失败
        return false;
    }

    //==============================================================================

    /**
     * 发送消息
     * @param targetUserName 发送目标的用户名
     * @param huanXinMessageType 消息类型
     * @param msg  消息
     * @return
     */
    @Override
    public Boolean sendMsgFromAdmin(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        try {
            String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/messages";

            //消息格式：{"target_type": "users","target": ["user2","user3"],"msg": {"type": "txt","msg": "testmessage"},"from": "user1"}
            String body = JSONUtil.createObj()          //  创建一个json格式对象 - {}       createArray() 创建一个json格式数组 - []

                    .set("target_type", "users")        //  {"target_type": "users"}

                    .set("target", JSONUtil.createArray().set(targetUserName))  //  {"target_type": "users", "target": ["HX_xxx"]}

                    //  {"target_type": "users", "target": ["HX_xxx"], "msg": {"type", "txt", "msg": "消息正文"}}
                    .set("msg", JSONUtil.createObj().set("type", huanXinMessageType.getType()).set("msg", msg))

                    //表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
                    //.set("from", "")

                    .toString();

            return requestService.execute(targetUrl, body, Method.POST).isOk();
        } catch (Exception e) {
            log.error("发送消息失败~ targetUserName = " + targetUserName+", type = " + huanXinMessageType.getType()+", msg = " + msg, e);
        }
        return false;
    }
}
